package main

import (
	"fmt"
	"math/rand"
	"time"
)

func try(fn func(), handler func(interface{})) {
	// 這不會馬上被執行，但當 panic 被執行就會結束程式，結束程式就必定會呼叫 defer
	defer func() {
		// 透過 recover 來從 panic 狀態中恢復，並呼叫捕捉函式
		if err := recover(); err != nil {
			handler(err)
		}
	}()
	// 執行可能帶有 panic 的程式
	fn()
}

func foo(number int) {
	if number < 10 {
		panic("number is less than 10")
	}
	if number > 10 {
		panic("number is greater than 10")
	}
}

func main() {
	r := rand.New(rand.NewSource(time.Now().Unix()))
	fmt.Println(r.Intn(10000))

	fmt.Println(time.Now())

	try(func() {
		foo(9)
	}, func(e interface{}) {
		fmt.Println(e) // 輸出：number is less than 10
	})

	try(func() {
		foo(11)
	}, func(e interface{}) {
		fmt.Println(e) // 輸出：number is greater than 10
	})
}